package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.feign.WmUserFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRealnameService;
import com.usian.user.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserRealnameService apUserRealnameService;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    //用户审核业务放在这 service写
    /**
     * 1:ap_user_realname  status  2:失败  9：通过
     * 2:ap_user  user
     * 3:feign  leadnews_wemedia.wm_user  insert
     * 4:feign  leadnews_article.ap_author insert
     * 5:update  ap_user  flag
     */

    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto) {
        if(dto ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getStatus()!=2 && dto.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_PARAM_INVALID);
        }

        //1:ap_user_realname  status  2:失败  9：通过
        ApUserRealname apUserRealname =new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        if(dto.getStatus()==2 &&dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        apUserRealnameService.updateById(apUserRealname);


        //2:获取用户对象  ap_user
        ApUserRealname userRealname = apUserRealnameService.getById(dto.getId());
        ApUser apUser = this.getById(userRealname.getUserId());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if(dto.getStatus() == 9){
            //2.1:远程保存wm_user  查自媒体账号如果存在不保存  不存在就保存
            WmUser wmUser = wmUserFeign.findByName(apUser.getName());
            if(wmUser==null){
                wmUser =new WmUser();
                wmUser.setApUserId(apUser.getId());
                wmUser.setCreatedTime(new Date());
                wmUser.setSalt(apUser.getSalt());
                wmUser.setName(apUser.getName());
                wmUser.setPassword(apUser.getPassword());
                wmUser.setStatus(9);
                wmUser.setPhone(apUser.getPhone());
                wmUserFeign.saveWmUser(wmUser);
            }

            //3:保存作者信息   有作者不保存  没有则保存
            ApAuthor apAuthor = apAuthorFeign.findByUserId(apUser.getId());
            if(apAuthor==null){
                apAuthor =new ApAuthor();
                apAuthor.setName(wmUser.getName());
                apAuthor.setType(2); //2:平台自媒体人
                apAuthor.setCreatedTime(new Date());
                apAuthor.setUserId(apUser.getId());
                apAuthor.setWmUserId(wmUser.getId());
                apAuthorFeign.saveApAuthor(apAuthor);
            }
        }

        //4:改 ap_user flag
        apUser.setFlag((short)1);
        this.updateById(apUser);

        //int a =1/0;

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult login(LoginDto dto) {

        //校验参数
        if((StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword())) && dto.getEquipmentId()==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        if(StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword())){
            //根据设备生成token 以0生成token
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }else{
            //根据账号生成token
            //根据用户名到数据库匹配用户数据
            QueryWrapper<ApUser> wrapper =new QueryWrapper<>();
            wrapper.lambda().eq(ApUser::getPhone,dto.getPhone());

            List<ApUser> list = this.list(wrapper);
            if(list!=null && list.size()>0){
                ApUser apUser = list.get(0); //从数据库查询出来的用户  加密密码    盐值

                String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                //新生成的密码  和 数据库加密后的密码比较
                if(apUser.getPassword().equals(newPwd)){
                    //正确  生成token  user
                    Map<String,Object> map = new HashMap<>();
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }else{
                    //输入错误
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_DATA_NOT_EXIST);

            }
        }
    }
}
